<template>
    <el-table :data="tableData" :span-method="spanMethod" border style="width: 100%" :row-style="{ height: '60px' }"
        :header-row-style="{ height: '60px' }" :header-cell-style="{ backgroundColor: '#FAF8F8 !important', color: 'rgba(16,16,16,1)', fontWeight: 'bold' }"
        :row-class-name="tableRowClassNameForHighlight">
        <el-table-column v-for="(col, idx) in columns" :key="idx" :label="col.label" :prop="col.prop"
            header-align="center" align="center" :width="col.width" :fixed="col.prop == 'operation' ? 'right': false">
            <template #default="scope">
               
                <!-- 输入行：显示输入框 -->
                <template v-if="scope.row.isInput && col.prop != 'group'">
                    <el-select v-model="selectGroupId" filterable remote clearable reserve-keyword
                        placeholder="请输入关键词 (如: 第五代)" :remote-method="remoteMethod" :loading="loading"
                        @change="handleSelectGroupChange" >
                        <el-option v-for="item in groupData" :key="item.id" :label="item.name" :value="item.id" />
                        <template #empty>
                            <p class="empty-tip">无匹配数据</p>
                        </template>
                    </el-select>
                </template>
                <!-- 套包输入框标识 -->
                <template v-if="scope.row.isSelect && col.prop != 'group'">
                    <el-select v-model="selectPairPackageId" filterable remote clearable reserve-keyword
                        placeholder="请输入关键词 (如: xxx套包)" :remote-method="remoteMethodPairPackage"
                        :loading="loadingPackage" @change="handleSelectPairPackageChange">
                        <el-option v-for="item in pairPackageData" :key="item.id" :label="item.packName"
                            :value="item.id" />
                        <template #empty>
                            <p class="empty-tip">无匹配数据</p>
                        </template>
                    </el-select>
                </template>
                <!-- 项目操作 -->
                <template v-if="col.prop == 'number' && scope.row.group == '项目'">
                    <!-- <el-input v-model="scope.row.number" placeholder="请输入数量" /> -->
                    <el-input-number v-model="scope.row.number" @change="handleInputNumberChange(scope.row)" :min="1" label="请输入数量" :controls="false" style="width: 100%;"></el-input-number>
                </template>
                <template v-if="col.prop == 'number' && scope.row.group == '套包合计'">
                    <span>{{ scope.row.number }}</span>
                </template>
                <template v-if="col.prop == 'operation' && scope.row.group == '项目'">
                    <el-button type="primary" @click="deleteGroup(scope.row, scope)" link>删除</el-button>
                </template>
                <!-- 套包名称 -->
                <template v-if="scope.row.isInputTotal && col.prop == 'name'">
                    <el-input v-model="pairPackageName" placeholder="请输入套包名称" />
                </template>
                <template v-if="scope.row.isInputTotal && col.prop == 'activityDiscount'">
                    <el-input v-model="activityValue" placeholder="请输入活动价格" @blur="activityValueBlur($event)" />
                </template>
                <!-- 套包操作 -->
                <template v-if="scope.row.isInputTotal && col.prop == 'operation'">
                    <div style="width: 100%;display: flex;align-items: center;justify-content: center;gap: 0 10px;">
                        <el-button type="primary" link @click="savePackFun">保存</el-button>
                        <el-button type="primary" link @click="deletePairPackage(scope.row)" v-if="packId">删除</el-button>
                    </div>
                </template>

                <!-- 查询行：显示可点击文本 -->
                <!-- 项目行：显示数据 -->
                <template v-if="col.prop != 'operation' && col.prop != 'group' && col.prop != 'number' && col.prop != 'activityDiscount' && col.prop != 'commissionAmount' && col.prop != 'checkbox'">
                    <div 
                        v-if="scope.row.isAddGroup && col.prop != 'group'"
                        :style="{ textAlign: scope.row.isAddGroup ? 'left' : 'center' }">
                        <span class="query-text"  @click="insertInputRow(scope)">{{ scope.row[col.prop] }}</span>
                        
                    </div>
                    <div 
                        v-else-if="scope.row.isAddTotal && col.prop != 'group'"
                        :style="{ textAlign: scope.row.isAddTotal ? 'left' : 'center' }">
                        <span class="query-text"  @click="insertInputRowTotal(scope)">{{ scope.row[col.prop] }}</span>
                        
                    </div>
                    <span v-else="!scope.row.isAddTotal && !scope.row.isAddGroup && col.prop != 'group'" :style="{fontWeight: col.prop == 'name' ? 'bold' : 500,color: 'rgba(16,16,16,1)'}">
                        {{ col.prop == 'name' ? scope.row[col.prop] : '￥' + scope.row[col.prop] }}
                    </span>
                </template>
                <template v-if="col.prop == 'commissionAmount'">
                    <span :style="{color: scope.row.group == '项目' ? '#F1813A !important' : ''}">￥{{ scope.row.commissionAmount }}</span>
                </template>
                <template v-if="col.prop == 'activityDiscount' && scope.row.group == '项目'">
                    <span style="color: #F1813A !important;">￥{{ scope.row.activityDiscount }}</span>
                </template>
                <template v-if="col.prop == 'group'">
                    <span style="font-weight: bold;color: rgba(16,16,16,1);">{{ scope.row.group }}</span>
                </template>
                <template v-if="col.prop == 'checkbox' && !scope.row.isAddTotal && !scope.row.isAddGroup && scope.row.group != '套包合计'">
                    <el-checkbox v-model="scope.row.isSend" @change="handleCheckboxChange($event, scope.row)"></el-checkbox>
                </template>
            </template>
        </el-table-column>
    </el-table>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, toRaw } from 'vue';
import { getProjectList, packList, projectListByPack, savePack, deletePack } from '@/api/port'
import { ElMessage, ElMessageBox } from 'element-plus'

// 新增
import { debounce } from 'lodash-es';
// 控制是否显示加载状态的动画
const loading = ref(false);

const originalProjectList = ref<Array<{
    [key: string]: any
}>>([])

const emit = defineEmits(['dataChange', 'init'])
// 修正后的表格数据
const tableData = ref<{
    [key: string]: any
}>([
    { group: '项目', name: '+ 根据项目名称 快速查询', isAddGroup: true },
    { group: '套包合计', name: '+ 根据套包名称 快速查询', isAddTotal: true }
])


// 修正后的列定义
const columns = [
    { label: '#', prop: 'group', width: 60 }, // 第一列（纵向合并）
    { label: '名称', prop: 'name', },
    { label: '原价', prop: 'price', width: 150 },
    { label: '出库产品及耗材成本', prop: 'costPrice', width: 172},
    { label: '医护操作费', prop: 'serviceFee', width: 160 },
    { label: '提点金额', prop: 'commissionAmount', width: 163 },
    { label: '数量', prop: 'number', width: 90 },
    { label: '赠送', prop: 'checkbox', width: 90 },
    { label: '活动折扣价', prop: 'activityDiscount', width: 110 },
    { label: '操作', prop: 'operation', width: 168}
];

// 输入框值
const activityValue = ref('');
const pairPackageName = ref('')

// 用于缓存每段连续 group 的 rowspan
let spanCache = buildSpanCache(tableData.value)

const spanMethod = ({ row, rowIndex, columnIndex }: any) => {
    // 只处理第一列（group 列）
    if (columnIndex === 0) {
        const { rowspan, isFirst } = spanCache[rowIndex] || {}
        return {
            rowspan: isFirst ? rowspan : 0,
            colspan: 1
        }
    } else if (row.isAddGroup) {
        return columnIndex === 1
            ? { rowspan: 1, colspan: columns.length - 1 }
            : { rowspan: 0, colspan: 0 };
    } else if (row.isAddTotal) {
        return columnIndex === 1
            ? { rowspan: 1, colspan: columns.length - 1 }
            : { rowspan: 0, colspan: 0 };
    } else if (row.isInput) {
        return columnIndex === 1
            ? { rowspan: 1, colspan: columns.length - 1 }
            : { rowspan: 0, colspan: 0 };
    } else if (row.isSelect) {
        return columnIndex === 1
            ? { rowspan: 1, colspan: columns.length - 1 }
            : { rowspan: 0, colspan: 0 };
    } else {
        return { rowspan: 1, colspan: 1 }
    }
}

// 构建 span 缓存，每段 group 的首项标 rowspan，其余项为 0
function buildSpanCache(data: any) {
    const cache = []
    let currentGroup = ''
    let count = 0
    let startIndex = 0

    data.forEach((row: any, i: number) => {
        if (row.group !== currentGroup) {
            // 保存上一段 group 的合并信息
            if (count > 0) {
                for (let j = startIndex; j < i; j++) {
                    cache[j] = {
                        rowspan: count,
                        isFirst: j === startIndex
                    }
                }
            }
            // 开始新的 group
            currentGroup = row.group
            count = 1
            startIndex = i
        } else {
            count++
        }
    })

    // 处理最后一段 group
    for (let j = startIndex; j < data.length; j++) {
        cache[j] = {
            rowspan: count,
            isFirst: j === startIndex
        }
    }

    return cache
}



// 点击查询行，插入输入行
function insertInputRow(row: any) {
    if (tableData.value.find((item: any) => item.isInput == true)) {
        return
    }
    tableData.value.splice(row.$index, 0, {
        isInput: true,
        group: '项目', // 保持第一列合并
        name: '' // 输入框内容
    });
    spanCache = buildSpanCache(tableData.value)
}

const insertInputRowTotal = (row: any) => {
    if (tableData.value.find((item: any) => item.isSelect == true)) {
        return
    }
    tableData.value.splice(row.$index, 0, {
        isSelect: true,
        group: '套包合计', // 保持第一列合并
        name: '' // 输入框内容
    });
    spanCache = buildSpanCache(tableData.value)
}




// 为特定的row设置class
const tableRowClassNameForHighlight = ({ row }: {
    row: any
    rowIndex: number
}) => {
    if (row.group === '套包合计') {
        return 'background-row';
    }
}

// 获取数据
const groupData = ref<Array<{
    [key: string]: any
}>>([])
const getProjectListFun = async () => {
    const res = await getProjectList({ keyword: '' })
    if (res.data.code == 0) {
        let list = res.data.data
        list.forEach((item: any) => {
            item.group = '项目'
        })
        groupData.value = list
    }
}
// 获取套包数据
const pairPackageData = ref<Array<{
    [key: string]: any
}>>([])
const getPairPackageListFun = async () => {
    const res = await packList({ keyword: '' })
    if (res.data.code == 0) {
        let list = res.data.data
        list.forEach((item: any) => {
            item.group = '套包合计'
        })
        pairPackageData.value = list
    }
}
// 选择项目
const selectGroupId = ref()
const handleSelectGroupChange = (value: any) => {
    selectGroupId.value = value
    let obj = groupData.value.find((item: any) => item.id == value)
    if(obj){
        originalProjectList.value.push(obj)
    } 
    if(tableData.value.some((item: any)=> item.id == value)){
        ElMessage.error('已存在相同项目, 请直接更改数量')
        selectGroupId.value = ''
        return false
    }
    let index = tableData.value.findIndex((item: any) => item.isInput == true)
    tableData.value.splice(index, 1, {
        group: '项目',
        name: obj?.name,
        operation: 'delete',
        price: obj?.price,
        costPrice: obj?.costPrice,
        serviceFee: computedPrice(obj, 'serviceFee'),
        activityDiscount: computedPrice(obj, 'activityDiscount'),
        commissionAmount: computedPrice(obj, 'commissionAmount'),
        isData: true,
        id: obj?.id,
        code: obj?.code,
        projectHandlingFee: obj?.projectHandlingFee,
        number: 1,
        commissionProportion: obj?.projectHandlingFee?.commissionProportion,
        isSend: false,
    })

    tableData.value.forEach((item: any) => {
        if (item.group == '项目' && item.isData) {
            item.serviceFee = computedPrice(item, 'serviceFee')
        }
    })
    selectGroupId.value = ''

    let totalObj = tableData.value.find((item: any) => item.isInputTotal == true)
    if (!totalObj) {
        tableData.value.splice(tableData.value.length - 1, 0, {
            group: '套包合计',
            name: '',
            operation: 'delete',
            isInputTotal: true,
            isDate: true,
            price: computedPriceTotal('price'),
            costPrice: computedPriceTotal('costPrice'),
            commissionAmount: computedPriceTotal('commissionAmount'),
            // serviceFee: computedPriceTotal('serviceFee'),
            serviceFee: Number((computedPriceArray().totalOperationFee).toFixed(2)),
            number: computedPriceTotal('number'),
        })
        pairPackageName.value = ''
        let selectIndex = tableData.value.findIndex((item: any) => item.isSelect)
        if (selectIndex > 0) {
            tableData.value.splice(selectIndex, 1)
        }
    } else {
        let index = tableData.value.findIndex((item: any) => item.isInputTotal == true)
        tableData.value[index].price = computedPriceTotal('price')
        tableData.value[index].costPrice = computedPriceTotal('costPrice')
        tableData.value[index].commissionAmount = computedPriceTotal('commissionAmount')
        // tableData.value[index].serviceFee = computedPriceTotal('serviceFee')
        tableData.value[index].serviceFee = Number((computedPriceArray().totalOperationFee).toFixed(2))
        tableData.value[index].number = computedPriceTotal('number')

        if (activityValue.value && Number(activityValue.value) != 0 && activityValue.value != '') {
            let computedTotalPrice = Number(computedPriceTotal('price'))
            tableData.value.forEach((item: any)=>{
                if(item.isSend){
                    computedTotalPrice = computedTotalPrice - Number(item.price)
                }
            })
            tableData.value.forEach((item: any)=>{
                if(item.group == '项目' && !item.isAddGroup){
                    let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
                    item.activityDiscount = !item.isSend ? price : 0
                    // 获取总价并确保为数值类型

                    // 确保活动值为数值类型
                    const activityVal = Number(activityValue.value)

                    // 获取佣金比例并确保为数值类型，默认0
                    const commissionRate = Number(item.commissionProportion || 1);

                    // 计算价格占比 * 活动值
                    const priceRatio = (item.price / computedTotalPrice) * activityVal;
                    // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
                    // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
                    const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
                    item.commissionAmount = !item.isSend ? finalValue : 0
                }
                if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
                    item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
                }
            })
            // tableData.value.forEach((item: any) => {
            //     if (item.group == '项目' && item.isData) {
            //         item.activityDiscount = ((item.price / Number(computedPriceTotal('price'))) * Number(activityValue.value)).toFixed(2)

            //         item.serviceFee = computedPrice(item, 'serviceFee')

            //         // 获取总价并确保为数值类型
            //         const totalPrice = Number(computedPriceTotal('price'));

            //         // 确保活动值为数值类型
            //         const activityVal = Number(activityValue.value);

            //         // 获取佣金比例并确保为数值类型，默认0
            //         const commissionRate = Number(item.projectHandlingFee?.commissionProportion || 0);

            //         // 计算价格占比 * 活动值
            //         const priceRatio = (item.price / totalPrice) * activityVal;

            //         // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            //         const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            //         // item.commissionAmount =  Number(
            //         //     Number((
            //         //         (item.price / Number(computedPriceTotal('price'))) * 
            //         //         Number(activityValue.value)
            //         //     ).toFixed(2)) * 
            //         //     Number(item.projectHandlingFee?.commissionProportion || 0)
            //         // ).toFixed(2)

            //         item.commissionAmount = finalValue
            //     }

            //     if(item.group == '套包合计' && item.isInputTotal){
            //         item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
            //     }
            // })
        }


    }
    spanCache = buildSpanCache(tableData.value)

    getProjectListFun()
}

// 选择套包
const selectPairPackageId = ref()
const packId = ref()
const handleSelectPairPackageChange = async (value: any) => {
    // console.log(value)
    tableData.value = tableData.value.filter((item: any) => item.isData == false || item.isData == null || item.isData == undefined)
    selectPairPackageId.value = value
    packId.value = value
    let obj = pairPackageData.value.find((item: any) => item.id == value)
    // let index = tableData.value.findIndex((item: any)=> item.isInput == true)
    const res = await projectListByPack({ packId: value })
    // console.log('=========================****************=========================', res, obj)
    originalProjectList.value = res.data.data
    if (res.data.code == 0) {
        res.data.data.forEach((item: any) => {
            tableData.value.unshift({
                group: '项目',
                name: item?.name,
                operation: 'delete',
                price: item?.price * item.projectHandlingFee?.number,
                costPrice: item?.costPrice * item.projectHandlingFee?.number,
                
                // commissionAmount: computedPrice(item, 'commissionAmount'),
                isData: true,
                id: item.id,
                code: item.code,
                projectHandlingFee: item?.projectHandlingFee,
                number: item?.projectHandlingFee.number,
                
                commissionProportion: item?.projectHandlingFee?.commissionProportion,
                // activityDiscount: computedPrice(item, 'activityDiscount'),
                isSend: item?.projectHandlingFee?.isSend == 1,
            })
        })
        

        
        // console.log(computedPriceArray())
        pairPackageName.value = obj?.packName
        if (obj?.activePrice != '' && obj?.activePrice != null) {
            let computedTotalPrice = Number(computedPriceTotal('price'))
            tableData.value.forEach((item: any)=>{
                if(item.isSend){
                    computedTotalPrice = computedTotalPrice - Number(item.price)
                }
            })
            tableData.value.forEach((item: any)=>{
                if(item.group == '项目' && !item.isAddGroup){
                    let price = Number(((item.price / computedTotalPrice) * Number(obj?.activePrice)).toFixed(2))
                    item.activityDiscount = !item.isSend ? price : 0
                    // 获取总价并确保为数值类型

                    // 确保活动值为数值类型
                    const activityVal = Number(obj?.activePrice)

                    // 获取佣金比例并确保为数值类型，默认0
                    const commissionRate = Number(item.commissionProportion || 1);

                    // 计算价格占比 * 活动值
                    const priceRatio = (item.price / computedTotalPrice) * activityVal;
                    // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
                    // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
                    const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
                    item.commissionAmount = !item.isSend ? finalValue : 0,
                    item.serviceFee = computedPrice(item, 'serviceFee')
                }
                if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
                    item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
                }
            })
            // tableData.value.forEach((item: any) => {
            //     if (item.group == '项目' && item.isData) {
                    
            //         item.activityDiscount = !item.isSend ? ((item.price / Number(computedPriceTotal('price'))) * Number(obj?.activePrice)).toFixed(2) : 0
            //         // item.commissionAmount = ((item.price / Number(computedPriceTotal('price'))) * Number(obj?.activePrice) * (Number(item.projectHandlingFee?.commissionProportion || 0))).toFixed(2)
            //         // console.log(Number(((item.price / Number(computedPriceTotal('price'))) * Number(obj?.activePrice)).toFixed(2)), Number(item.projectHandlingFee?.commissionProportion || 0))
            //         item.serviceFee = computedPrice(item, 'serviceFee')
            //         // 获取总价并确保为数值类型
            //         const totalPrice = Number(computedPriceTotal('price'));

            //         // 确保活动值为数值类型
            //         const activityVal = Number(obj?.activePrice);

            //         // 获取佣金比例并确保为数值类型，默认0
            //         const commissionRate = Number(item.projectHandlingFee?.commissionProportion || 0);

            //         // 计算价格占比 * 活动值
            //         const priceRatio = (item.price / totalPrice) * activityVal;

            //         // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            //         const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);

            //         item.commissionAmount = !item.isSend ? finalValue : 0
            //         // item.commissionAmount =  Number(Number(((item.price / Number(computedPriceTotal('price'))) * Number(obj?.activePrice)).toFixed(2)) * Number(item.projectHandlingFee?.commissionProportion || 0)).toFixed(2)
            //     }

            //     if(item.group == '套包合计' && item.isInputTotal){
            //         item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
            //     }
            // })
            activityValue.value = obj?.activePrice
        }
        let index = tableData.value.findIndex((item: any) => item.isInputTotal == true)
        tableData.value.splice(index >= 0 ? index : tableData.value.length - 2, 1, {
            group: '套包合计',
            name: '',
            operation: 'delete',
            isInputTotal: true,
            isDate: true,
            price: computedPriceTotal('price'),
            costPrice: computedPriceTotal('costPrice'),
            commissionAmount: computedPriceTotal('commissionAmount'),
            // serviceFee: computedPriceArray().totalOperationFee,
            serviceFee: Number((computedPriceArray().totalOperationFee).toFixed(2)),
            id: obj?.id,
            number: computedPriceTotal('number'),
        })
        let selectObj = tableData.value.findIndex((item: any) => item.isSelect == true)
        if (selectObj > 0) {
            tableData.value.splice(selectObj, 1)
        }
    }

    spanCache = buildSpanCache(tableData.value)

    selectPairPackageId.value = ''
    getPairPackageListFun()

}

// 计算每一项的金额
const computedPrice = (data: any, tag: string) => {
    // console.log('computedPrice=======================',toRaw(data))
    if (data.group == '套包合计') return 0
    if (data == null) return 0
    let price = 0
    if (tag == 'commissionAmount') {
        let obj = tableData.value.find((item: any) => item.isInputTotal)
        let jine = 0
        if(!obj) {
            jine = 0
        }else{
            jine = Number((((data.price) / Number(computedPriceTotal('price'))) * Number(activityValue.value)).toFixed(2))
            // console.log('jine=======================',jine,'======================',data?.commissionProportion)
        }
        price = Number((Number(jine) * (Number(data?.commissionProportion || 0))).toFixed(2))
    }
    if (tag == 'serviceFee') {
        price = Number((Number(data.projectHandlingFee?.circulatingNurseHandlingFee * data.number || 0) +
            Number(data.projectHandlingFee?.deskNurseHandlingFee * data.number || 0) +
            Number(data.projectHandlingFee?.doctorHandlingFee * data.number || 0) +
            Number(data.projectHandlingFee?.injectionsNurseHandlingFee * data.number || 0) +
            Number(data.projectHandlingFee?.nurseHandlingFee * data.number || 0) +
            Number(data.projectHandlingFee?.scrubNurseHandlingFee * data.number || 0)).toFixed(2))

        console.log(price)
    }
    if (tag == 'activityDiscount') {
        // console.log('data================================data=========================',data)
        let obj = tableData.value.find((item: any) => item.isInputTotal)
        if(!obj) {
            price = 0
        }else{
            // console.log('obj====================', (data.price / Number(computedPriceTotal('price'))))
            price = Number(((data.price / Number(computedPriceTotal('price'))) * Number(activityValue.value)).toFixed(2))
        }
    }

    return price

}
// 计算套包合计每一项的金额
// const totalPrice = ref(0)
const computedPriceTotal = (tag: string) => {
    let list = tableData.value.filter((item: any) => item.group == '项目' && item.isData)
    let price = 0
    list.forEach((item: any) => {
        
        if (tag == 'price') {
            price += Number(item.price)
        }
        if (tag == 'costPrice') {
            price += Number(item.costPrice)
        }
        if (tag == 'commissionAmount') {
            price += Number(item.commissionAmount)
        }
        if (tag == 'serviceFee') {
            price += Number(item.serviceFee)
        }
        if(tag == 'number'){
            price += Number(item.number)
        }
    })
    // if (tag == 'price') {
    //     totalPrice.value = price
    // }
    return tag == 'number' ? price : price.toFixed(2)

}

// 活动价格失焦
const activityValueBlur = (event: any) => {
    console.log(event)
    if (event.target.value == '' || event.target.value == 0) {
        return
    }

    // tableData.value.forEach((item: any) => {
    //     if (item.group == '项目' && item.isData) {
    //         item.activityDiscount = Number(((item.price / Number(computedPriceTotal('price'))) * Number(event.target.value)).toFixed(2))
    //         // 获取总价并确保为数值类型
    //         const totalPriceValue = Number(computedPriceTotal('price'));

    //         // 确保活动值为数值类型
    //         const activityVal = Number(event.target.value);

    //         // 获取佣金比例并确保为数值类型，默认0
    //         const commissionRate = Number(item.projectHandlingFee?.commissionProportion || 0);

    //         // 计算价格占比 * 活动值
    //         const priceRatio = (item.price / totalPriceValue) * activityVal;

    //         // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
    //         const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
    //         item.commissionAmount = finalValue
    //         // 更新 commissionAmount
    //         // item.commissionAmount =  Number(Number(((item.price / Number(computedPriceTotal('price'))) * Number(event.target.value)).toFixed(2)) * Number(item.projectHandlingFee?.commissionProportion || 0)).toFixed(2)
    //     }

    //     if(item.group == '套包合计' && item.isInputTotal){
    //         item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
    //     }
    // })
    
    let computedTotalPrice = Number(computedPriceTotal('price'))
    tableData.value.forEach((item: any)=>{
        if(item.isSend){
            computedTotalPrice = computedTotalPrice - Number(item.price)
        }
    })
    tableData.value.forEach((item: any)=>{
        if(item.group == '项目' && !item.isAddGroup){
            let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
            item.activityDiscount = !item.isSend ? price : 0
            // 获取总价并确保为数值类型

            // 确保活动值为数值类型
            const activityVal = Number(activityValue.value)

            // 获取佣金比例并确保为数值类型，默认0
            const commissionRate = Number(item.commissionProportion || 1);

            // 计算价格占比 * 活动值
            const priceRatio = (item.price / computedTotalPrice) * activityVal;
            // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
            // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            item.commissionAmount = !item.isSend ? finalValue : 0
        }
        if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
            item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
        }
    })

    spanCache = buildSpanCache(tableData.value)
}

const pageChange = () => {
    if(activityValue.value == '') {
        ElMessage({
            message: '请填写套包活动价格.',
            type: 'warning',
        })
        return
    }
    let list = tableData.value.filter((item: any) => item.isData)
    if (list.length == 0) {
        ElMessage({
            message: '您还没有配置需要预测的数据.',
            type: 'warning',
        })
        return
    }
    ElMessageBox.confirm(
        '您确定要进行预测吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    ).then(() => {
        let totalObj = tableData.value.find((item: any) => item.group == '套包合计' && item.isInputTotal)
        console.log(totalObj)
        emit('dataChange', { activityValue: activityValue.value, ...totalObj })

    }).catch(() => {
        console.log('取消预测')
    })
}

// 删除项目
const deleteGroup = (row: any, obj: any) => {
    console.log(row, obj)
    ElMessageBox.confirm(
        `您确定要删除${row.name}吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    ).then(() => {
        tableData.value.splice(obj.$index, 1)

        computedPairPackage()
        spanCache = buildSpanCache(tableData.value)
    }).catch(() => {
        console.log('取消预测')
    })
}
// 删除套包
const deletePairPackage = (row: any) => {
    console.log(toRaw(row))
    ElMessageBox.confirm(
        `您确定要删除吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    ).then( async () => {
        await deletePack({packId: row.id})
        emit('init')
        getPairPackageListFun()
        ElMessage({
            message: '删除成功.',
            type: 'success',
        })
    }).catch(() => {
        console.log('取消预测')
    })
}
// 套包保存
const savePackFun = () => {
    if (pairPackageName.value == '') {
        ElMessage({
            message: '请填写套包名称.',
            type: 'warning',
        })
        return
    }
    if (activityValue.value == '') {
        ElMessage({
            message: '请填写套包活动价格.',
            type: 'warning',
        })
        return
    }
    let list = tableData.value.filter((item: any) => item.group == '项目' && item.isData)
    let projectList = ref<Array<{
        crmProjectId: string,
        projectNo: string
        number: number,
        isSend: number,
    }>>([])
    if (list.length == 0) {
        ElMessage({
            message: '您还没有配置需要保存的项目数据.',
            type: 'warning',
        })
        return
    } else {
        list.forEach((item: any) => {
            projectList.value.push({
                crmProjectId: item.id,
                projectNo: item.code,
                number: item.number,
                isSend: item.isSend == true ? 1 : 0,
            })
        })
    }
    ElMessageBox.confirm(
        `您确定要保存现在配置的套包吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    ).then(async () => {
        console.log('projectList=========================', toRaw(projectList.value))
        let obj = {
            packId: packId.value,
            packName: pairPackageName.value,
            activePrice: activityValue.value,
            projectList: projectList.value
        }

        let res = await savePack(obj)
        console.log(res)
        if(res.data.code == 0){
            ElMessage({
                message: '保存成功.',
                type: 'success',
            })
        }else{
            ElMessage({
                message: res.data.msg,
                type: 'error',
            })
        }
    }).catch(() => {
        console.log('取消预测')
    })
}

// 套包计算
const computedPairPackage = async () => {
    let index = tableData.value.findIndex((item: any) => item.isInputTotal == true)
    if (index < 0) return
    // console.log('index===========================', index)

    tableData.value.splice(index >= 0 ? index : tableData.value.length - 2, 1, {
        group: '套包合计',
        name: '',
        operation: 'delete',
        isInputTotal: true,
        isDate: true,
        price: computedPriceTotal('price'),
        costPrice: computedPriceTotal('costPrice'),
        // commissionAmount: computedPriceTotal('commissionAmount'),
        serviceFee: Number((computedPriceArray().totalOperationFee).toFixed(2)),
        number: computedPriceTotal('number'),
    })
    let computedTotalPrice = Number(computedPriceTotal('price'))
    tableData.value.forEach((item: any)=>{
        if(item.isSend){
            computedTotalPrice = computedTotalPrice - Number(item.price)
        }
    })
    tableData.value.forEach((item: any)=>{
        if(item.group == '项目' && !item.isAddGroup){
            let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
            item.activityDiscount = !item.isSend ? price : 0
            // 获取总价并确保为数值类型

            // 确保活动值为数值类型
            const activityVal = Number(activityValue.value)

            // 获取佣金比例并确保为数值类型，默认0
            const commissionRate = Number(item.commissionProportion || 1);

            // 计算价格占比 * 活动值
            const priceRatio = (item.price / computedTotalPrice) * activityVal;
            // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
            // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            item.commissionAmount = !item.isSend ? finalValue : 0
        }
        if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
            item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
        }
    })
    // tableData.value.forEach((item: any) => {
    //     if (item.group == '项目' && item.isData) {
    //         // console.log('222222222222222', computedPrice(item, 'activityDiscount'))
    //         item.activityDiscount = !item.isSend ? computedPrice(item, 'activityDiscount') : 0
    //         // 获取总价并确保为数值类型
    //         const totalPrice = Number(computedPriceTotal('price'));

    //         // 确保活动值为数值类型
    //         const activityVal = Number(activityValue.value)

    //         // 获取佣金比例并确保为数值类型，默认0
    //         const commissionRate = Number(item.commissionProportion || 1);

    //         // 计算价格占比 * 活动值
    //         const priceRatio = (item.price / totalPrice) * activityVal;
    //         console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
    //         // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
    //         const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
    //         item.commissionAmount = !item.isSend ? finalValue : 0
    //         // 将最终结果赋值给 item.commissionAmount
    //         // item.commissionAmount =  Number(Number(((item.price / Number(computedPriceTotal('price'))) * Number(obj?.activePrice)).toFixed(2)) * Number(item.projectHandlingFee?.commissionProportion || 0)).toFixed(2)
    //     }

    //     if(item.group == '套包合计' && item.isInputTotal){
    //         item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
    //     }
    // })
}


// 初始化
const initializePage = () => {
    tableData.value = [
        { group: '项目', name: '+ 根据项目名称 快速查询', isAddGroup: true },
        { group: '套包合计', name: '+ 根据套包名称 快速查询', isAddTotal: true }
    ]
    activityValue.value = ''
    spanCache = buildSpanCache(tableData.value)
}


// 新增
const performSearch = async (query: any) => {
    console.log(query)
    if(query == ''){
        return
    }
    loading.value = true; // 开始搜索，显示加载状态
    try {
        // 调用 API 获取数据
        const result = await getProjectList({ keyword: query });
        if (result.data.code == 0) {
            let list = result.data.data
            list.forEach((item: any) => {
                item.group = '项目'
            })
            groupData.value = list
        }
    } catch (error) {
        // console.error('数据获取失败:', error);
        groupData.value = []; // 发生错误时清空列表
    } finally {
        loading.value = false; // 搜索结束，隐藏加载状态
    }
};
const loadingPackage = ref(false)
const performPairPackageSearch = async (query: any) => {
    console.log(query)
    if(query == ''){
        return
    }
    loadingPackage.value = true; // 开始搜索，显示加载状态
    try {
        // 调用 API 获取数据
        const res = await packList({ keyword: query })
        // console.log(res)
        if (res.data.code == 0) {
            let list = res.data.data
            list.forEach((item: any) => {
                item.group = '套包合计'
            })
            pairPackageData.value = list
        }
    } catch (error) {
        // console.error('数据获取失败:', error);
        groupData.value = []; // 发生错误时清空列表
    } finally {
        loadingPackage.value = false; // 搜索结束，隐藏加载状态
    }
    
};
const remoteMethod = debounce(performSearch, 300);


const remoteMethodPairPackage = debounce(performPairPackageSearch, 300)



// 三种规则计算
const computedPriceArray = () => {
    const result = {
        // 护士配台1相关统计（注射-玻尿酸、再生材料、胶原、水光针）
        nurseType1: {
            totalCount: 0,         // 总数量
            maxHandlingFee: 0      // 最高操作费金额
        },
        // 各类注射项目的最高价格
        injectionPrices: {
            botox: 0,             // 肉毒素
            other: 0,             // 其他注射
            lipolysis: 0,         // 溶脂针
            disposable: 0,        // 配台一次性
            mesotherapy: 0        // 美塑
        },
        // 酷塑项目统计
        coolsculpting: {
            totalCount: 0,        // 总数量
            maxHandlingFee: 0     // 最高操作费金额
        },
        normalOperationFee: 0,  // 正常项目的医生护士操作费总和
        totalOperationFee: 0    // 总操作费
    };
    const baseFee = ref(0)
    const otherFees = ref(0)
    console.log(toRaw(tableData.value))
    tableData.value.forEach((item: any) => {
        if(item.group == '项目' && item.isData && item.projectHandlingFee){
            // console.log(item)
            const { 
                doctorNursePriceType, 
                injectionsNurseHandlingFee,
                doctorHandlingFee,
                nurseHandlingFee,
                deskNurseHandlingFee,
                scrubNurseHandlingFee,
                circulatingNurseHandlingFee
            } = item.projectHandlingFee;
            // console.log(doctorNursePriceType, item.number, injectionsNurseHandlingFee, doctorHandlingFee, nurseHandlingFee, deskNurseHandlingFee, scrubNurseHandlingFee, circulatingNurseHandlingFee)
            if(item.projectHandlingFee && item.projectHandlingFee.doctorNursePriceType != '' && item.projectHandlingFee.doctorNursePriceType != null && item.projectHandlingFee.doctorNursePriceType != '正常'){
                // 2.1 护士配台1类型（注射-玻尿酸、再生材料、胶原、水光针）
                if (['注射-玻尿酸', '注射-再生材料', '注射-胶原', '注射-水光针'].includes(doctorNursePriceType)) {
                    result.nurseType1.totalCount += item.number; // 累加总数量
                    if (injectionsNurseHandlingFee > result.nurseType1.maxHandlingFee) {
                        result.nurseType1.maxHandlingFee = injectionsNurseHandlingFee; // 更新最高操作费
                    }

                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                }
                // 2.2 各类注射项目（肉毒素、其他、溶脂针、配台一次性、美塑）
                else if (doctorNursePriceType === '注射-肉毒素') {
                    if (injectionsNurseHandlingFee > result.injectionPrices.botox) {
                        result.injectionPrices.botox = injectionsNurseHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                } 
                else if (doctorNursePriceType === '注射-其他') {
                    if (injectionsNurseHandlingFee > result.injectionPrices.other) {
                        result.injectionPrices.other = injectionsNurseHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                } 
                else if (doctorNursePriceType === '注射-溶脂针') {
                    if (injectionsNurseHandlingFee > result.injectionPrices.lipolysis) {
                        result.injectionPrices.lipolysis = injectionsNurseHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                } 
                else if (doctorNursePriceType === '配台一次性') {
                    if (injectionsNurseHandlingFee > result.injectionPrices.disposable) {
                        result.injectionPrices.disposable = injectionsNurseHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                } 
                else if (doctorNursePriceType === '美塑') {
                    if (injectionsNurseHandlingFee > result.injectionPrices.mesotherapy) {
                        result.injectionPrices.mesotherapy = injectionsNurseHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                    // console.log('result.normalOperationFee===========================================',result.normalOperationFee)
                }
                // 2.3 酷塑项目
                else if (doctorNursePriceType === '酷塑') {
                    result.coolsculpting.totalCount += item.number;
                    if (doctorHandlingFee > result.coolsculpting.maxHandlingFee) {
                        result.coolsculpting.maxHandlingFee = doctorHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (injectionsNurseHandlingFee * item.number);
                }
                // 2.4 正常项目
                else {
                    result.coolsculpting.totalCount += item.number;
                    if (doctorHandlingFee > result.coolsculpting.maxHandlingFee) {
                        result.coolsculpting.maxHandlingFee = doctorHandlingFee;
                    }
                    result.normalOperationFee += (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number) + (injectionsNurseHandlingFee * item.number);
                    // // 计算正常项目的医生护士操作费
                    // baseFee.value = (injectionsNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                    // otherFees.value = (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number);
                    // result.normalOperationFee += baseFee.value + otherFees.value;
                }
            }
            else{
                // 计算正常项目的医生护士操作费
                baseFee.value = (injectionsNurseHandlingFee * item.number) + (doctorHandlingFee * item.number);
                otherFees.value = (nurseHandlingFee * item.number) + (deskNurseHandlingFee * item.number) + (scrubNurseHandlingFee * item.number) + (circulatingNurseHandlingFee * item.number);
                result.normalOperationFee += baseFee.value + otherFees.value;
            }
        }
    })
    // 3. 计算总操作费
    // 向上取整函数
    const ceilDiv = (numerator: number, denominator: number) => Math.ceil(numerator / denominator);
    
    result.totalOperationFee = (
        // 护士配台1费用：(总数量/2)向上取整 * 最高操作费
        ceilDiv(result.nurseType1.totalCount, 2) * result.nurseType1.maxHandlingFee +
        // 各类注射项目最高价格总和
        result.injectionPrices.botox +
        result.injectionPrices.other +
        result.injectionPrices.lipolysis +
        result.injectionPrices.disposable +
        result.injectionPrices.mesotherapy +
        // 酷塑项目费用：(总数量/4)向上取整 * 最高操作费
        ceilDiv(result.coolsculpting.totalCount, 4) * result.coolsculpting.maxHandlingFee +
        // 正常项目操作费
        result.normalOperationFee
    );
    // console.log('=result=result======================',result)
    return result;

}

// 改变数量
const handleInputNumberChange = (params: any) => {
    console.log(toRaw(params))
    tableData.value.forEach((item: any) => {
        if(item.id == params.id){
            let obj = originalProjectList.value.find((item: any) => item.id == params.id)
            item.price = Number((obj?.price * params.number).toFixed(2))
            item.costPrice = Number((obj?.costPrice * params.number).toFixed(2))
            item.serviceFee = Number((computedPrice(item, 'serviceFee')).toFixed(2))
            // item.commissionAmount = Number((computedPrice(item, 'commissionAmount')).toFixed(2))
            // item.activityDiscount = Number((computedPrice(obj, 'activityDiscount') * params.number).toFixed(2))
        }

        
    })
    let computedTotalPrice = Number(computedPriceTotal('price'))
    tableData.value.forEach((item: any)=>{
        if(item.isSend){
            computedTotalPrice = computedTotalPrice - Number(item.price)
        }
    })
    tableData.value.forEach((item: any) => {
        if(item.group == '项目' && item.isData && !item.isAddGroup){
            
            let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
            item.activityDiscount = !item.isSend ? price : 0
            // 获取总价并确保为数值类型

            // 确保活动值为数值类型
            const activityVal = Number(activityValue.value)

            // 获取佣金比例并确保为数值类型，默认0
            const commissionRate = Number(item.commissionProportion || 1);

            // 计算价格占比 * 活动值
            const priceRatio = (item.price / computedTotalPrice) * activityVal;
            // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
            // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            item.commissionAmount = !item.isSend ? finalValue : 0
                
            
            // item.activityDiscount = Number((computedPrice(item, 'activityDiscount')).toFixed(2))
            // // 获取总价并确保为数值类型
            // const totalPrice = Number(computedPriceTotal('price'));

            // // 确保活动值为数值类型
            // const activityVal = Number(activityValue.value)

            // // 获取佣金比例并确保为数值类型，默认0
            // const commissionRate = Number(item.commissionProportion || 1);

            // // 计算价格占比 * 活动值
            // const priceRatio = (item.price / totalPrice) * activityVal;
            // console.log('priceRatio', toRaw(item))
            // // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            // const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            // item.commissionAmount = finalValue
            // item.commissionAmount = Number((computedPrice(item, 'commissionAmount')).toFixed(2))
        }

        

        if (item.group == '套包合计' && item.isInputTotal) {
            item.number = computedPriceTotal('number')
            item.price = computedPriceTotal('price'),
            item.costPrice = computedPriceTotal('costPrice'),
            item.commissionAmount = Number(computedPriceTotal('commissionAmount')),
            item.serviceFee = Number((computedPriceArray().totalOperationFee).toFixed(2))
        }
    })
}


// checkbox 变化之后的计算  为 true 时
// const computedCheckbox = async (params: any) =>{
//     let computedTotalPrice = Number(computedPriceTotal('price'))
//     tableData.value.forEach((item: any)=>{
//         if(item.isSend){
//             computedTotalPrice = computedTotalPrice - Number(params.price * params.number)
//         }
//     })
//     tableData.value.forEach((item: any)=>{
//         if(item.group == '项目' && params.id == item.id){
//             item.activityDiscount = 0
//             item.commissionAmount = 0
//         }
//         if(item.group == '项目' && params.id != item.id && !item.isAddGroup){
//             let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
//             item.activityDiscount = !item.isSend ? price : 0
//             // 获取总价并确保为数值类型

//             // 确保活动值为数值类型
//             const activityVal = Number(activityValue.value)

//             // 获取佣金比例并确保为数值类型，默认0
//             const commissionRate = Number(item.commissionProportion || 1);

//             // 计算价格占比 * 活动值
//             const priceRatio = (item.price / computedTotalPrice) * activityVal;
//             // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
//             // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
//             const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
//             item.commissionAmount = !item.isSend ? finalValue : 0
//         }
//         if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
//             item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
//         }
//     })
// }

// // checkbox 变化之后的计算  为 false 时
// const computedCheckbox_vice = async (params: any) =>{
//     let obj = tableData.value.find((item: any)=> item.id == params.id)
//     tableData.value.forEach((item: any)=>{
//         if(item.group == '项目' && params.id == item.id && !item.isAddGroup){
//             // console.log('222222222222222', computedPrice(item, 'activityDiscount'))
//             item.activityDiscount = computedPrice(item, 'activityDiscount')
//             // 获取总价并确保为数值类型
//             const totalPrice = Number(computedPriceTotal('price'));

//             // 确保活动值为数值类型
//             const activityVal = Number(activityValue.value)

//             // 获取佣金比例并确保为数值类型，默认0
//             const commissionRate = Number(item.commissionProportion || 1);

//             // 计算价格占比 * 活动值
//             const priceRatio = (item.price / totalPrice) * activityVal;
//             console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
//             // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
//             const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
//             item.commissionAmount = finalValue
//         }
//         if(item.group == '项目' && params.id != item.id && !item.isAddGroup){
//             // console.log('222222222222222', computedPrice(item, 'activityDiscount'))
//             item.activityDiscount = !item.isSend ? computedPrice(item, 'activityDiscount') : 0
//             // 获取总价并确保为数值类型
//             const totalPrice = Number(computedPriceTotal('price'));

//             // 确保活动值为数值类型
//             const activityVal = Number(activityValue.value)

//             // 获取佣金比例并确保为数值类型，默认0
//             const commissionRate = Number(item.commissionProportion || 1);

//             // 计算价格占比 * 活动值
//             const priceRatio = (item.price / totalPrice) * activityVal;
//             console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
//             // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
//             const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
//             item.commissionAmount = !item.isSend ? finalValue : 0
//         }
//         if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
//             item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
//         }
//     })
// }



// 每一个赠送change
const handleCheckboxChange = async (event: any, item: any) => {
    console.log(event, toRaw(item))

    let computedTotalPrice = Number(computedPriceTotal('price'))
    tableData.value.forEach((item: any)=>{
        if(item.isSend){
            computedTotalPrice = computedTotalPrice - Number(item.price)
        }
    })
    tableData.value.forEach((item: any)=>{
        if(item.group == '项目' && !item.isAddGroup){
            let price = Number(((item.price / computedTotalPrice) * Number(activityValue.value)).toFixed(2))
            item.activityDiscount = !item.isSend ? price : 0
            // 获取总价并确保为数值类型

            // 确保活动值为数值类型
            const activityVal = Number(activityValue.value)

            // 获取佣金比例并确保为数值类型，默认0
            const commissionRate = Number(item.commissionProportion || 1);

            // 计算价格占比 * 活动值
            const priceRatio = (item.price / computedTotalPrice) * activityVal;
            // console.log('priceRatio', priceRatio, totalPrice, activityVal, item.price, toRaw(item))
            // 计算最终结果：(价格比例 * 佣金比例) / 100，并保留两位小数
            const finalValue = ((priceRatio * commissionRate) / 100).toFixed(2);
            item.commissionAmount = !item.isSend ? finalValue : 0
        }
        if(item.group == '套包合计' && item.isInputTotal && !item.isAddTotal){
            item.commissionAmount = Number(computedPriceTotal('commissionAmount'))
        }
    })
}



defineExpose({
    pageChange,
    initializePage
})

onMounted(async () => {
    await nextTick()
    await getProjectListFun()
    await getPairPackageListFun()
})
</script>

<style scoped>
.query-text {
    color: #409eff;
    cursor: pointer;
    /* text-decoration: underline; */
}

.el-table .background-row {
    background-color: #f0f9eb;
    /* 一个自定义的淡绿色 */
}

.background-row {
    background-color: #FAF8F8 !important;
}

:deep(.background-row .el-table__cell) {
    background: #FAF8F8 !important;
}
:deep(.el-table--border .el-table__inner-wrapper:after){
    height: 0 !important;
}
</style>